package com.xlh.service.courseTest.impl;

import com.google.common.collect.Lists;
import com.xlh.dao.courseTest.CourseTestPaperQuestionMapper;
import com.xlh.dao.courseTest.CourseTestPaperQuestionMapperExt;
import com.xlh.dto.courseTest.PaperTypeDTO;
import com.xlh.dto.courseTest.QuestionDTO;
import com.xlh.pojo.courseTest.*;
import com.xlh.service.courseTest.PaperAnswerService;
import com.xlh.service.courseTest.PaperQuestionService;
import com.xlh.service.courseTest.QuestionRepositoryDetailsService;
import com.xlh.service.courseTest.QuestionRepositoryService;
import com.xlh.util.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhr 2019/3/2
 */
@Service
public class PaperQuestionServiceImpl implements PaperQuestionService {

    @Autowired
    private PaperAnswerService answerService;
    @Autowired
    private QuestionRepositoryService questionRepositoryService;
    @Autowired
    private QuestionRepositoryDetailsService questionRepositoryDetailsService;

    @Autowired
    private CourseTestPaperQuestionMapper questionMapper;
    @Autowired
    private CourseTestPaperQuestionMapperExt questionMapperExt;

    @Override
    public void deleteByPaperId(Long paperId) {
        CourseTestPaperQuestionExample example = new CourseTestPaperQuestionExample();
        example.createCriteria().andPaperIdEqualTo(paperId);
        questionMapper.deleteByExample(example);
    }

    @Override
    public List<CourseTestPaperQuestion> selectByPaperId(Long paperId) {
        CourseTestPaperQuestionExample example = new CourseTestPaperQuestionExample();
        example.createCriteria().andPaperIdEqualTo(paperId);
        List<CourseTestPaperQuestion> result = questionMapper.selectByExampleWithBLOBs(example);
        return CollectionUtils.isEmpty(result) ? Lists.newArrayList() : result;
    }

    @Override
    public void insertPaperQuestion(Long paperId, List<PaperTypeDTO> questionParamList) {
        // 题型-得分映射集
        Map<Integer, Integer> typeScoreMap = questionParamList.stream()
                .collect(Collectors.toMap(PaperTypeDTO::getType, PaperTypeDTO::getScore));

        List<Long> questionIds = Lists.newArrayList();
        questionParamList.stream().map(param -> param.getContent().stream().map(QuestionDTO::getQuestionId)
                .collect(Collectors.toList())).forEach(questionIds::addAll);

        // 题目列表
        List<CourseQuestionRepository> questionList = questionRepositoryService.selectQuestionByIds(questionIds);
        // 答案列表映射（按照题目id映射）
        Map<Long, List<CourseQuestionRepositoryDetails>> answerListQuestionMap = questionRepositoryDetailsService.getDetailsMap(questionIds);

        // 批量插入题目队列
        List<CourseTestPaperQuestion> paperQuestionList = Lists.newArrayList();
        // 批量插入答案队列
        List<CourseTestPaperAnswer> paperAnswerList = Lists.newArrayList();

        int orderNumber = 0;
        for (CourseQuestionRepository question : questionList) {
            CourseTestPaperQuestion paperQuestion = new CourseTestPaperQuestion(++orderNumber, question, paperId, typeScoreMap.get(question.getQuestionType()));
            paperQuestionList.add(paperQuestion);
        }

        if (CollectionUtils.isNotEmpty(paperQuestionList)) questionMapperExt.insertBatch(paperQuestionList);

        for (CourseTestPaperQuestion question : paperQuestionList) {
            // 答案映射中更新新的questionId
            if (answerListQuestionMap.get(question.getOriginQuestionId()) != null) {
                answerListQuestionMap.get(question.getOriginQuestionId()).forEach(answer -> answer.setQuestionId(question.getId()));
            }
        }

        for (List<CourseQuestionRepositoryDetails> list : answerListQuestionMap.values()) {
            for (CourseQuestionRepositoryDetails answer : list) {
                CourseTestPaperAnswer paperAnswer = BeanUtil.transform(CourseTestPaperAnswer.class, answer);
                if (paperAnswer != null) {
                    paperAnswerList.add(paperAnswer);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(paperAnswerList)) answerService.insertBatch(paperAnswerList);

    }

    @Override
    public CourseTestPaperQuestion selectQuestionById(Long id) {
        return questionMapper.selectByPrimaryKey(id);
    }

    @Override
    public void cleanData() {
        questionMapperExt.cleanData();
    }

    @Override
    public List<CourseTestPaperQuestion> selectFirstQuestionByPaperIds(List<Long> paperIds) {
        if (CollectionUtils.isEmpty(paperIds)) {
            return Lists.newArrayList();
        }
        CourseTestPaperQuestionExample example = new CourseTestPaperQuestionExample();
        example.createCriteria().andPaperIdIn(paperIds).andOrderNumberEqualTo(1);
        List<CourseTestPaperQuestion> list = questionMapper.selectByExample(example);
        return CollectionUtils.isEmpty(list) ? Lists.newArrayList() : list;
    }
}
